<template>
  <!-- 添加或修改用户配置对话框 -->
  <el-dialog
    :title="title"
    :visible.sync="open"
    append-to-body
    width="70%"
    @close="handleClose"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <div class="form-block">
        <div class="form-block-title">基本信息</div>

        <el-row>
          <el-col :span="8">
            <el-form-item label="基地名称" prop="name">
              <el-input
                v-model.trim="form.name"
                placeholder="请输入基地名称"
                class="input-width"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="基地面积" prop="area">
              <el-input
                v-model.number="form.area"
                placeholder="请输入基地面积"
                class="input-width"
              >
                <template slot="append">亩</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="所属区域" prop="districtId">
              <el-cascader
                class="input-width"
                v-model="form.districtId"
                :options="deptOptions"
                :show-all-levels="true"
                :props="{
                  expandTrigger: 'click',
                  checkStrictly: false,
                  value: 'deptId',
                  label: 'deptName',
                  emitPath: false,
                }"
                placeholder="请选择所属区域"
                filterable
                clearable
                @change="handleDeptChange"
                ref="CascaderRef"
              ></el-cascader>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="详细地址" prop="address">
              <el-input
                v-model="form.address"
                placeholder="请输入详细地址"
                class="input-width"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="基建成本" prop="constructionCost">
              <el-input
                v-model="form.constructionCost"
                placeholder="请输入基建成本"
                class="input-width"
              >
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="备注">
              <el-input
                v-model="form.remarks"
                type="textarea"
                placeholder="请输入备注信息"
                class="input-width"
                :autosize="{ minRows: 1, maxRows: 6 }"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item label="基地照片">
            <ImageUpload v-model="form.fileUrls"></ImageUpload>
          </el-form-item>
        </el-row>
      </div>
      <div v-show="form.id">
        <el-row class="form-block">
          <el-col :span="24">
            <div class="form-block-title">关联塘口</div>
          </el-col>
          <el-col :span="24">
            <ul class="relevance-card">
              <li class="first" @click="handleOpenPond('add')" @mouseover="pondHover=true" @mouseout="pondHover=false" :class="{'hover-scale':pondHover}">
                <i class="el-icon-plus"></i>
              </li>
              <li v-for="(item, index) in form.culturePondList" :key="item.id">
                <div class="relevance-card-content">
                  <div>
                    <ImagePreview
                      :src="item.fileUrls || placeholderImg"
                      :width="70"
                      :height="70"
                    ></ImagePreview>
                  </div>
                  <div class="pl-10">
                    <p class="title_18px">{{ item.name }}</p>
                    <p>
                      <span class="title_gray">面积：{{ item.area }}亩</span>
                    </p>
                    <p>
                      <span class="title_gray"
                        >设备：{{ item.deviceCnt }}台</span
                      >
                    </p>
                  </div>
                </div>
                <div class="relevance-card-footer">
                  <div>
                    <span class="title_gray"
                      >养殖：</span
                    >{{ item.breedSpecies || "无" }}
                  </div>
                  <div>
                    <el-button
                      type="text"
                      icon="el-icon-edit"
                      @click="handleOpenPond('edit', item.id)"
                    ></el-button>
                    <el-button
                      type="text"
                      icon="el-icon-delete"
                      class="btn-danger"
                      @click="handleRemovePond(index)"
                    ></el-button>
                  </div>
                </div>
              </li>
            </ul>
          </el-col>
        </el-row>

        <el-row class="form-block">
          <el-col :span="24">
            <div class="form-block-title">关联设备</div>
          </el-col>
          <el-col :span="24">
            <ul class="relevance-card">
              <li class="first" @click="handleOpenEquipment('add')" @mouseover="equipmentHover=true" @mouseout="equipmentHover=false" :class="{'hover-scale':equipmentHover}">
                <i class="el-icon-plus"></i>
              </li>
              <li v-for="(item, index) in form.deviceList" :key="item.id">
                <div class="relevance-card-content">
                  <div>
                    <ImagePreview
                      :src="item.fileUrls || placeholderImg"
                      :width="70"
                      :height="70"
                    ></ImagePreview>
                  </div>
                  <div class="pl-10">
                    <p class="title_18px">{{ item.name }}</p>
                    <p>
                      <span class="title_gray">编号：{{ item.code }}</span>
                    </p>
                    <p>
                      <span class="title_gray"
                        >绑定区域：{{
                          item.culturePondName
                            ? item.culturePondName
                            : item.productionBaseName
                        }}</span
                      >
                    </p>
                  </div>
                </div>
                <div class="relevance-card-footer">
                  <div>
                    <span class="title_gray">投运日期：</span
                    >{{ item.useDate || "-" }}
                  </div>
                  <div v-if="!item.culturePondId">
                    <el-button
                      type="text"
                      icon="el-icon-edit"
                      @click="handleOpenEquipment('edit', item.id)"
                    ></el-button>
                    <el-button
                      type="text"
                      icon="el-icon-delete"
                      class="btn-danger"
                      @click="handleRemoveEquipment(index)"
                    ></el-button>
                  </div>
                </div>
              </li>
            </ul>
          </el-col>
        </el-row>

        <el-row class="form-block">
          <el-col :span="24">
            <div class="form-block-title">关联人员</div>
          </el-col>
          <el-col :span="24">
            <ul class="relevance-card">
              <li class="first" @click="handleOpenPersonnel('add')" @mouseover="personnelHover=true" @mouseout="personnelHover=false" :class="{'hover-scale':personnelHover}">
                <i class="el-icon-plus"></i>
              </li>
              <li v-for="(item, index) in form.userList" :key="item.id">
                <div class="relevance-card-content">
                  <div>
                    <ImagePreview
                      :src="item.avatar || placeholderImg"
                      :width="70"
                      :height="70"
                    ></ImagePreview>
                  </div>
                  <div class="pl-10">
                    <p class="title_18px">{{ item.username }}</p>
                    <p>
                      <span class="title_gray">角色：{{ item.roleNames }}</span>
                    </p>
                    <p>
                      <span class="title_gray">管理区域：</span>{{ item.culturePondNames || item.productionBaseNames }}
                    </p>
                  </div>
                </div>
                <div class="relevance-card-footer">
                  <div>
                    <span class="title_gray">手机号：</span
                    >{{ item.phonenumber || "-" }}
                  </div>
                  <div v-if="!item.culturePondNames">
                    <el-button
                      type="text"
                      icon="el-icon-edit"
                      @click="handleOpenPersonnel('edit', item.userId)"
                    ></el-button>
                    <el-button
                      type="text"
                      icon="el-icon-delete"
                      class="btn-danger"
                      @click="handleRemovePersonnel(index)"
                    ></el-button>
                  </div>
                </div>
              </li>
            </ul>
          </el-col>
        </el-row>
      </div>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="handleSubmit">{{
        form.id ? "确 定" : "创建基地"
      }}</el-button>
      <el-button @click="handleClose">关 闭</el-button>
    </div>
    <!-- <PondSelect
      :visible.sync="pondOpen"
      :params="pondParams"
      @selection="handlePondSelection"
    ></PondSelect> -->
    <PondEdit
      :visible.sync="pondOpen"
      :params="pondParams"
      @success="getDetail"
    ></PondEdit>
    <EquipmentEdit
      :visible.sync="equipmentOpen"
      :params="equipmentParams"
      @success="getDetail"
    ></EquipmentEdit>
    <PersonnelEdit
      :visible.sync="personnelOpen"
      :params="personnelParams"
      @success="getDetail"
    ></PersonnelEdit>
  </el-dialog>
</template>

<script>
import { detail, update, add } from "@/api/production/base";
import { deptTreeSelect } from "@/api/system/user";
import ImageUpload from "@/components/ImageUpload";
import ImagePreview from "@/components/ImagePreview";
// import PondSelect from "@/views/production/pond/select.vue";
import PondEdit from "@/views/production/pond/edit.vue";
import EquipmentEdit from "@/views/production/equipment/edit.vue";
import PersonnelEdit from "@/views/production/personnel/edit.vue";

export default {
  name: "production-base_add",
  dicts: ["sys_normal_disable", "sys_user_sex"],
  components: {
    ImageUpload,
    ImagePreview,
    PondEdit,
    EquipmentEdit,
    PersonnelEdit,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    params: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    return {
      pondHover:false,
      equipmentHover:false,
      personnelHover:false,
      placeholderImg: require("@/assets/images/production.png"),
      pondOpen: false, // 塘口模态框
      pondParams: { type: "add", title: "关联塘口", baseId: 0 }, // 塘口传递数据
      equipmentOpen: false,
      equipmentParams: { type: "add", title: "关联设备", baseId: 0 },
      personnelOpen: false,
      personnelParams: { type: "add", title: "关联人员", baseId: 0 },
      queryParams: { id: undefined },
      title: "",
      // 是否显示弹出层
      open: false,
      // 行政区划树选项
      deptOptions: undefined,
      // 表单
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "基地名称不能为空", trigger: "blur" },
        ],
        area: [
          { required: true, message: "基地面积不能为空", trigger: "blur" },
        ],
        districtId: [
          { required: true, message: "所属区域不能为空", trigger: "change" },
        ],
        address: [
          { required: true, message: "详细地址不能为空", trigger: "change" },
        ],
        constructionCost: [
          { required: true, message: "基建成本不能为空", trigger: "change" },
        ],
      },
    };
  },
  watch: {
    visible: {
      handler(val) {
        this.open = val;
        this.getDeptTree();
        if (val && this.params.type == "edit") {
          this.queryParams.id = this.params.id;
          this.getDetail();
        }
        if (val) {
          this.title = this.params.title;
        }
      },
    },
  },
  methods: {
    // 移除人员
    handleRemovePersonnel(index) {
      this.form.userList.splice(index, 1);
    },
    /** 关联人员 */
    handleOpenPersonnel(type = "add", id) {
      if (type === "add") {
        this.personnelParams = {
          type: "add",
          title: "关联人员",
          baseId: this.form.id,
          fromBase: true,
        };
      } else if (type === "edit") {
        this.personnelParams = {
          type: "edit",
          title: "修改人员信息",
          id,
          autoClose: true,
          fromBase: true,
        };
      }
      this.personnelOpen = true;
    },
    // 移除设备
    handleRemoveEquipment(index) {
      this.form.deviceList.splice(index, 1);
    },
    /** 关联设备 */
    handleOpenEquipment(type = "add", id) {
      if (type === "add") {
        this.equipmentParams = {
          type: "add",
          title: "关联设备",
          baseId: this.form.id,
          fromBase: true,
        };
      } else if (type === "edit") {
        this.equipmentParams = {
          type: "edit",
          title: "修改设备信息",
          id,
          autoClose: true,
          fromBase: true,
        };
      }
      this.equipmentOpen = true;
    },
    // 移除塘口
    handleRemovePond(index) {
      this.form.culturePondList.splice(index, 1);
    },
    /** 关联塘口 */
    handleOpenPond(type = "add", pondId) {
      if (type === "add") {
        this.pondParams = {
          type: "add",
          title: "关联塘口",
          baseId: this.form.id,
          fromBase: true,
        };
      } else if (type === "edit") {
        this.pondParams = {
          type: "edit",
          title: "修改塘口信息",
          id: pondId,
          autoClose: true,
        };
      }
      this.pondOpen = true;
    },
    getDetail() {
      detail(this.queryParams).then((res) => {
        this.form = res.data;
      });
    },
    /** 查询行政区划下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then((response) => {
        this.deptOptions = this.removeEmptyChildren(response.data);
      });
    },
    // 选择站办所
    handleDeptChange(val) {
      let findVal = this.findDeptHierarchy(this.deptOptions, val);
      if (findVal) {
        this.form.districtName = findVal[0]["deptName"];
        this.form.cityId = findVal[1]["deptId"];
        this.form.cityName = findVal[1]["deptName"];
        this.form.provinceId = findVal[2]["deptId"];
        this.form.provinceName = findVal[2]["deptName"];
      }
      this.$refs.CascaderRef.dropDownVisible = false;
    },
    findDeptHierarchy(data, targetDeptId) {
      const result = [];

      function recurse(nodes, targetDeptId, hierarchy) {
        for (let node of nodes) {
          const currentHierarchy = [
            ...hierarchy,
            { deptId: node.deptId, deptName: node.deptName },
          ];

          // 如果找到目标deptId，返回当前的层级
          if (node.deptId === targetDeptId) {
            result.push(...currentHierarchy.reverse()); // 反转是因为我们希望上级在前
            return true;
          }

          // 否则继续遍历子节点
          if (node.children && node.children.length > 0) {
            if (recurse(node.children, targetDeptId, currentHierarchy)) {
              return true; // 如果递归找到，则返回
            }
          }
        }
        return false; // 如果没找到
      }
      recurse(data, targetDeptId, []);
      return result.length ? result : null; // 如果找不到，返回null
    },
    isNonEmptyArray(variable) {
      return Array.isArray(variable) && variable.length > 0;
    },
    /** 提交按钮 */
    handleSubmit() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id) {
            console.log(this.form);
            if (this.isNonEmptyArray(this.form.culturePondList))
              this.form.culturePondIdList = this.form.culturePondList.map(
                (item) => item.id
              );
            if (this.isNonEmptyArray(this.form.deviceList))
              this.formdeviceIdList = this.form.deviceList.map(
                (item) => item.id
              );
            if (this.isNonEmptyArray(this.form.userList))
              this.formuserIdList = this.form.userList.map((item) => item.id);

            update(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.$emit("success");
            });
          } else {
            add(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.$emit("success");
              this.$set(this.form, "id", response.data);
              this.form.id = response.data;
              this.queryParams.id = response.data;
            });
          }
        }
      });
    },
    // 取消按钮
    handleClose() {
      this.$emit("update:visible", false);
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        name: "",
        area: "",
        districtId: "",
        address: "",
        constructionCost: "",
        remarks: "",
      };
      this.resetForm("form");
    },
  },
};
</script>

<style scoped lang="scss">
.relevance-card {
  // display: flex;
  // flex-wrap: wrap;
  // justify-content: space-around;
  & > li {
    width: 24%;
    height: 120px;
    float: left;
    margin-right: calc(4% / 3);
    margin-bottom: calc(4% / 3);
    border-radius: 3px;
    background-color: #fff;
    padding: 10px;
    box-sizing: border-box;
    box-shadow: 0 0 3px 0 rgba($color: #000000, $alpha: 0.1);
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    overflow: hidden;
    &:nth-child(4n) {
      margin-right: 0;
    }
    &:nth-last-child(-n + 4) {
      // margin-bottom: 0;
    }
    .relevance-card-content {
      width: 100%;
      display: flex;

      & > img {
        width: 70px;
        height: 70px;
        margin-right: 10px;
        flex-shrink: 0;
      }
    }
    .relevance-card-footer {
      width: 100%;
      // height: 10%;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }
  .first {
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 46px;
    font-weight: 600;
    color: #eee;
    cursor: pointer;
  }
}
</style>